import api from '../../api/api'
import {
  urlObj
} from '../../api/url'
const app = getApp()
const wxCharts = require('../../utils/wxcharts-min.js');
let lineChart = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    location: {
      latitude: '',
      longitude: ''
    },
    scale: 12,
    polyline: [],
    markers: [],
    option: [],
    index: 0,
    showDialog: false,
    markerItem: {},
    deviceDetail: {},
    keyWord:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: options => {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDeviceType()
    this.getDeviceList({})
    this.getLoc()
  },
  getLoc() {
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        const latitude = res.latitude
        const longitude = res.longitude
        console.log('当前位置', longitude, latitude)
        this.setData({
          'location.longitude': longitude,
          'location.latitude': latitude
        })
      }
    })
  },
  regionchange(e) {
  },
  //点击merkers
  markertap(e) {
    console.log(e)
    this.data.markers.forEach(item => {
      if (item.id === e.detail.markerId) {
        console.log(item)
        this.setData({
          markerItem: item
        })
        let id = e.detail.markerId;
        wx.navigateTo({
          url: `../detail/detail?id=${id}&name=${this.data.markerItem.devicename}&latitude=${this.data.markerItem.latitude}&longitude=${this.data.markerItem.longitude}`
        })
        // this.getDeviceDetail(item.id)
        // this.getBarChartData(item.id)
      }
    })
    //弹窗
    // this.setData({
    //   showDialog: true
    // })
  },
  tapHere() {
    this.handleRoutePlan(this.data.markerItem)
  },
  handleRoutePlan(params) {
    console.log(params)
    //跳转腾讯地图小程序的路线规划  （v1）
    let plugin = requirePlugin('routePlan');
    let key = 'PEABZ-SMB63-L423H-YNJ44-M6Q67-LKFJW';
    let referer = '小程序专用';
    let endPoint = JSON.stringify({  //终点
      'name': params.devicename,
      'latitude': params.latitude,
      'longitude': params.longitude
    });
    wx.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
    });
  },
  handleTap(e) {
    console.log(e)
  },
  // 获取设别型号
  getDeviceType() {
    api.get(urlObj.getdevicetype).then(res => {
      if (res.statusCode == '200') {
        const targetArr = res.data.map(item => {
          return item.name
        })
        targetArr.unshift('全部')
        this.setData({
          option: targetArr
        })
      } else {
        console.log(res.msg)
      }
    })
  },
  //获取设备列表
  getDeviceList(searchParams) {
    const params = {
      limit: 50,
      page: 1,
      key: searchParams.key || '',
      name: searchParams.name || ''
    }
    wx.showLoading()
    api.get(urlObj.deviceList, params).then(res => {
      wx.hideLoading()
      if (res.statusCode == '200') {
        let { items } = res.data;
        if(items) {
          let iconPath =  "../../images/marker.png";
          let targetArr = items.map(item => {
            if(item.onlinestatus == 1){
              if(item.iserror=='03')  {
                iconPath =  "../../images/marker.png";
              } else{
                iconPath =  "../../images/marker3.png";
              }
            }else {
              iconPath =  "../../images/marker2.png";
            }
            return {
              id: item.deviceid,
              latitude: item.latitude,
              longitude: item.longitude,
              width: 32,
              height: 32,
              iconPath: iconPath,
              title: item.devicename,
              ...item
            }
          })
          this.setData({
            markers: targetArr
          })
        } else {
          this.setData({
            markers: []
          })
        }
      } else {
        console.log(res.msg)
      }
    })
  },
  // 获取设备详情
  getDeviceDetail(id) {
    const params = {
      deviceId: id
    }
    api.get(urlObj.deviceDetail, params).then(res => {
      if (res.statusCode == '200') {
        let { data } = res;
        for( let key in data) {
            data[key] = data[key] || '0'
        }
        this.setData({
          deviceDetail: data
        })
      }
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
    let key = '';
    this.data.option[this.data.index] == '全部' ?  key = '' : key = this.data.option[this.data.index]
    const searchForm = {
      key:key,
      name:this.data.keyWord
    }
    this.getDeviceList(searchForm)
  },
  handleInput(e) {
    let timer = null;
    let keyWord = e.detail.value ? e.detail.value : null ;
    if(timer){
        clearTimeout(timer)
    }
    timer = setTimeout(()=>{
        if(keyWord==null){
           //这里表示  如果搜索框中没有数据的话，做的一些处理
        }else{
          this.setData({
            keyWord:keyWord
          })
          let key = '';
          this.data.option[this.data.index] == '全部' ?  key = '' : key = this.data.option[this.data.index]
          const searchParams = {
            key:key,
            name:keyWord
          }
          this.getDeviceList(searchParams)
        }  
    },1000)
  },
  handleSearchData(){
    console.log('222')
    if(this.data.keyWord && this.data.keyWord.length > 0) {
      let key = '';
      this.data.option[this.data.index] == '全部' ?  key = '' : key = this.data.option[this.data.index]
      const searchParams = {
        key:key,
        name:this.data.keyWord
      }
      this.getDeviceList(searchParams)
    }
  },
  buttontap(e) {
    console.log(e.detail)
  },
  createSimulationData() {
    // data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  getBarChartData(id) {
    const params = {
      deviceId: id
    }
    api.get(urlObj.getChartData, params).then(res => {
      if (res.statusCode == '200') {
        let { data } = res;
        let targetItem = data.resData.result.data.items;
        // 异常处理
        if(!targetItem) {
          return false
        }
        let cate = targetItem.map(item => {
          return (item.createtime.split(' ')[1])
        })
        let acurrentData = targetItem.map(item => {
          return item.acurrent
        })
        let bcurrentData = targetItem.map(item => {
          return item.acurrent
        })
        let ccurrentData = targetItem.map(item => {
          return item.ccurrent
        })
        let avoltageData = targetItem.map(item => {
          return item.avoltage
        })
        let bvoltageData = targetItem.map(item => {
          return item.bvoltage
        })
        let cvoltageData = targetItem.map(item => {
          return item.cvoltage
        })
        let atemperatureData = targetItem.map(item => {
          return item.atemperature
        })
        let btemperatureData = targetItem.map(item => {
          return item.btemperature
        })
        let ctemperatureData = targetItem.map(item => {
          return item.ctemperature
        })
        const option1 = {
          dataCate: ['A相电流', 'B相电流', 'C相电流'],
          categories: cate,
          data1: acurrentData,
          data2: bcurrentData,
          data3: ccurrentData,
        }
        const option2 = {
          dataCate: ['A电缆电压', 'B电缆电压', 'C电缆电压'],
          categories: cate,
          data1: avoltageData,
          data2: bvoltageData,
          data3: cvoltageData,
        }
        const option3 = {
          dataCate: ['A电缆温度', 'B电缆温度', 'C电缆温度'],
          categories: cate,
          data1: atemperatureData,
          data2: btemperatureData,
          data3: ctemperatureData,
        }
        this.drawAnchart('lineCanvas', option1)
        this.drawAnchart('lineCanvas2', option2)
        this.drawAnchart('lineCanvas3', option3)
      }
    })
  },
   //初始化图表
   drawAnchart(id, options) {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    new wxCharts({
      canvasId: id,
      type: 'line',
      categories: options.categories,
      animation: true,
      background: '#f5f5f5',
      series: [{
        name: options.dataCate[0],
        data: options.data1,
        format: function (val, name) {
          return val.toFixed(2);
        }
      }, {
        name: options.dataCate[1],
        data: options.data2,
        format: function (val, name) {
          return val.toFixed(2);
        }
      }, {
        name: options.dataCate[2],
        data: options.data3,
        format: function (val, name) {
          return val.toFixed(2);
        }
      }],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        show: false,
        title: '',//y轴标题
        format: function (val) {
          return val.toFixed(2);
        },
        min: 0
      },
      width: windowWidth,
      height: 200,
      dataLabel: false,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  },
})